import argparse
import numpy as np

def hex_to_int(args):
    data_car = np.loadtxt(args.file_name, dtype=np.str, delimiter=" ", unpack=False)
    data_car = data_car[:, :11]
    data_car = data_car.reshape(data_car.size)
    data_car_int = []
    for data_hex in data_car:
        data_int = '0x' + data_hex
        data_car_int.append(int(data_int, 16))
    data_car_int = np.array(data_car_int)
    data_car_int = np.reshape(data_car_int, (-1, 11))
    return data_car_int

def data_denoise(array_data):
    radio = 0.8
    data_new = []
    old_value = array_data[0]
    for i in range(array_data.size):
        new_value = array_data[i]*radio + old_value*(1-radio)
        old_value = new_value
        data_new.append(new_value)
    data = np.array(data_new)
    return data

def ad_array_extension(x_ad_data, batch_size):
    data_len = x_ad_data.shape[0]
    ad_list = []
    for i in range(data_len):
        if i > batch_size:
            ad_list.append(x_ad_data[i-batch_size:i])
        else:
            ad_list.append(x_ad_data[0:batch_size])
    x_ad_data = np.array(ad_list)
    return x_ad_data

if __name__ == '__main__':
    """设置命令行参数"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-f',
        '--file_name',
        type=str,
        default='normal.txt',
        help='设置用于转换成训练格式的数据文件,如:normal.txt'
    )
    parser.add_argument(
        '--batch_size',
        type=int,
        default=1,
        help='设置训练时的batch_size'
    )
    args = parser.parse_args()

    data_car_int = hex_to_int(args) #数据整理：将十六进制转化为十进制
    batch_size = args.batch_size    #获取batch_size

    list_car = []
    for data in data_car_int:
        if data[10] != 90:
            print(data)
            raise ValueError('Error Data!')
            break
        time = data[0]<<8 + data[1]
        l, ml, m, mr, r, fl, fr, pwm = data[2], data[3], data[4], data[5], \
                                       data[6], data[7], data[8], data[9]
        list_car.append([l,ml,m,mr,r,fl,fr,pwm])
    list_car = np.array(list_car, dtype='int8')
    
    """划分训练集x(ad采集值),y(pwm值)"""
    x_ad_data = list_car[:, :-1]
    y_pwm_data = list_car[:, -1]
    # print(x_ad_data.shape)
    # print(x_ad_data[:5])
    # 一阶低通滤波
    ad_l = data_denoise(x_ad_data[:, 0])
    ad_ml = data_denoise(x_ad_data[:, 1])
    ad_m = data_denoise(x_ad_data[:, 2])
    ad_mr = data_denoise(x_ad_data[:, 3])
    ad_r = data_denoise(x_ad_data[:, 4])
    ad_fl = data_denoise(x_ad_data[:, 5])
    ad_fr = data_denoise(x_ad_data[:, 6])
    y_pwm_data = data_denoise(y_pwm_data) 
    x_ad_data = np.c_[ad_l, ad_ml, ad_m, ad_mr, ad_r, ad_fl, ad_fr]
    x_ad_data = x_ad_data.astype('int8')
    x_ad_data = ad_array_extension(x_ad_data, batch_size) #按照batch_size划分数据
    origin_ad = x_ad_data.astype('int8')
    origin_pwm = y_pwm_data.astype('int8')
    
    # 将处理好的数据保存起来
    filename = args.file_name.split('\\')[-1]
    filename = filename.split('.')[0]
    ad_filename = 'origin_ad_' + filename + '.npy'
    pwm_filename = 'origin_pwm_' + filename + '.npy'
    np.save(ad_filename, origin_ad)
    np.save(pwm_filename, origin_pwm)

    print("Generate ad.npy shape:", x_ad_data.shape)
    print("Generate pwm.npy shape:", y_pwm_data.shape)
    print('ad data shape:%f~%f' % (min(origin_ad.flatten()), max(origin_ad.flatten())))
    print('pwm data shape:%f~%f' % (min(origin_pwm), max(origin_pwm)))
    print('Generate %s,%s'%(pwm_filename,ad_filename))
